import json

import requests

from wechat_api.api.wework_api import WeWork


class Tag(WeWork):
    def search(self):
        data = {
            "url":"https://qyapi.weixin.qq.com/cgi-bin/externalcontact/get_corp_tag_list",
            "method":"post",
            "params":{"access_token":self.token},
            "json":{}
        }
        return self.request(data)


    def add(self, tag_name, group_name):
        data = {
            "url": "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/add_corp_tag",
            "method": "post",
            "params": {"access_token": self.token},
            "json": {
                "group_name": group_name,
                "tag":
                    [
                        {"name": tag_name}
                    ]
            }
        }
        # r = requests.post(
        #     "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/add_corp_tag",
        #     params={"access_token": self.token},
        #     json={
        #         "group_name": group_name,
        #         "tag":
        #             [
        #                 {"name": tag_name}
        #             ]
        #     }
        # )
        return self.request(data)


    def modify(self, tag_id, new_tag_name):
        data = {
            "url": "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/edit_corp_tag",
            "method": "post",
            "params": {"access_token": self.token},
            "json": {
                "id": tag_id,
                "name": new_tag_name
            }
        }
        # r = requests.post(
        #     "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/edit_corp_tag",
        #     params={"access_token": self.token},
        #     json={
        #         "id": tag_id,
        #         "name": new_tag_name
        #     }
        # )
        # print(json.dumps(r.json(), indent=2, ensure_ascii=False))
        return self.request(data)


    def delete(self, tag_id_list):
        data = {
            "url": "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/del_corp_tag",
            "method": "post",
            "params": {"access_token": self.token},
            "json": {
                "tag_id": tag_id_list
            }
        }
        # r = requests.post(
        #     "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/del_corp_tag",
        #     params={"access_token": self.token},
        #     json={
        #         "tag_id": tag_id
        #     }
        # )
        # print(json.dumps(r.json(), indent=2, ensure_ascii=False))
        return self.request(data)

    def clear(self):
        r = self.search()
        tag_id_list = [tag['id'] for group in r.json()['tag_group'] for tag in group['tag']]
        r = self.delete(tag_id_list)
        return r